<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use PHPMailer\PHPMailer\PHPMailer;
use Qcloud\Sms\SmsMultiSender;

class LoginController extends Controller
{

	public function __construct()
	{
//		跨域解决办法
	}

	/**
	 * 登陆接口
	 * @param Request $request
	 * @return string
	 */
	public function login(Request $request){
//		接值
		$input = $request->all();
		if(!isset($input["name"]) || !isset($input['password']) ) {
			$result = ['success'=>'false',"code"=>"-1","value"=>'账号或密码不能为空'];//账号密码不能为空
			return json_encode($result);
		}
		$username = trim($input['name'],"");
		$password = trim($input['password'],"");
		if(strlen($username) < 4){
			$result = ['success'=>'false',"code"=>"-1","value"=>'登录账号长度不能少于4位有效字符'];
			return json_encode($result);
		};
		if(strlen($password) < 4){
			$result = ['success'=>'false',"code"=>"-1","value"=>'登录密码长度不能少于4位有效字符'];
			return json_encode($result);
		};
		$user_info = DB::table("boke_user")->where(['name' => $input['name']])->first();
		if (empty($user_info)){
			$user_info = DB::table("boke_user")->where(['email' => $input['name']])->first();
		}
		if (empty($user_info)){
			$user_info = DB::table("boke_user")->where(['phone' => $input['name']])->first();
		}
		$user_info = (array)$user_info;
		if(empty($user_info)) {
			$result = ['success'=>'false',"code"=>"-1","value"=>'用户名不存在'];//用户名不存在
			return json_encode($result);
		}
		$password = md5($input['password']);
		if($user_info['password'] !== $password) {
			$result = ['success'=>'false',"code"=>"-1","value"=>'账号密码错误'];//账号密码错误
			return json_encode($result);
		}
		$result = ['success'=>'true',"code"=>"0","value"=>'登陆成功'];//登陆成功

		$login_record = DB::table("boke_login_record")->where("uid",$user_info['id'])->first();
		$login_record = (array)$login_record;
		$ip = $this->getIp();

		//开启事务
		DB::beginTransaction();
		try{
			if(empty($login_record)) {
				$data = [
					"uid" => $user_info['id'],
					"lastIP" => $ip,
					"logintime" => time(),
					"createtime" => time(),
				];
				DB::table("boke_login_record")->insert($data);
			}else{
				$data = [
					"lastIP" => $ip,
					"logintime" => time(),
				];
				DB::table("boke_login_record")->where("uid",$user_info['id'])->update($data);
			}
			session("user_info",$user_info);
			//中间逻辑代码 DB::commit();
			DB::commit();
		}catch (\Exception $e) {
			//接收异常处理并回滚 DB::rollBack();
			DB::rollBack();
		}
		return json_encode($result);
	}

	/**
	 * 注册接口
	 * @param Request $request
	 * @return string
	 */
	public function sign_up(Request $request) {
		$input = $request->all();
		$array = ["name"=>"用户名","password"=>"密码","pic_url"=>"头像"];
		foreach ($array as $k => $v) {
			if(!isset($input[$k])) {
				$result = ['success'=>'false',"code"=>"-1","value"=>'请输入'.$v];//不能为空
				return json_encode($result);
			}
		}
		$user = DB::table("boke_user")->where(['name' => $input['name']])->first();
		if(!empty($user)) {
			$result = ['success'=>'false',"code"=>"-1","value"=>'该用户名已存在'];//
			return json_encode($result);
		}
		if($input['status'] == 1) {//代表手机号注册
			if(!isset($input['phone'])) {
				$result = ['success'=>'false',"code"=>"-1","value"=>'请输入手机号'];//不能为空
				return json_encode($result);
			}
			$phone = DB::table("boke_user")->where(['phone' => $input['phone']])->first();
			if(!empty($phone)) {
				$result = ['success'=>'false',"code"=>"-1","value"=>'注册失败,该手机号已存在'];//
				return json_encode($result);
			}
			$code = DB::table("boke_code")->where(["phone"=>$input['phone']])->where("endtime",">",time())->first();
			$code = (array)$code;
			if(!empty($code)) {
				if(isset($code['code']) && $code['code'] != $input['code']) {
					$result = ['success'=>'false',"code"=>"-1","value"=>'验证码错误'];//
					return json_encode($result);
				}
			}else{
				$result = ['success'=>'false',"code"=>"-1","value"=>'验证码已过期'];//
				return json_encode($result);
			}
		}
		if($input['status'] == 2) {//代表邮箱注册
			if(!isset($input['email']))
			{
				$result = ['success'=>'false',"code"=>"-1","value"=>'请输入邮箱'];//不能为空
				return json_encode($result);
			}
			$email = DB::table("boke_user")->where(['email' => $input['email']])->first();
			if(!empty($email)) {
				$result = ['success'=>'false',"code"=>"-1","value"=>'注册失败,该邮箱已存在'];//
				return json_encode($result);
			}
			$code = DB::table("boke_code")->where(["email"=>$input['email']])->where("endtime",">",time())->first();
			$code = (array)$code;
			if(!empty($code)) {
				if(isset($code['code']) && $code['code'] != $input['code']) {
					$result = ['success'=>'false',"code"=>"-1","value"=>'验证码错误'];//
					return json_encode($result);
				}
			}else{
				$result = ['success'=>'false',"code"=>"-1","value"=>'验证码已过期'];//
				return json_encode($result);
			}
		}
		$data = [
			"name" => $input["name"],
			"password" => md5($input['password']),
			"nickname" => $input["nickname"],
			"phone" => isset($input["phone"]) ? $input["phone"] : '',
			"email" => isset($input["email"]) ? $input["email"] : '',
			"pic_url" => $input["pic_url"],
			"status" => 2,//代表用户
		];
		DB::table("boke_user")->insert($data);
		$result = ['success'=>'true',"code"=>"0","value"=>'注册成功'];//
		return json_encode($result);
	}

	/**
	 * 获取ip地址
	 * @return array|false|string
	 */
	function getIp(){
		$onlineip='';
		if(getenv('HTTP_CLIENT_IP')&&strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')){
			$onlineip=getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR')&&strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')){
			$onlineip=getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR')&&strcasecmp(getenv('REMOTE_ADDR'),'unknown')){
			$onlineip=getenv('REMOTE_ADDR');
		} elseif(isset($_SERVER['REMOTE_ADDR'])&&$_SERVER['REMOTE_ADDR']&&strcasecmp($_SERVER['REMOTE_ADDR'],'unknown')){
			$onlineip=$_SERVER['REMOTE_ADDR'];
		}
		return $onlineip;
	}

	/**
	 * 获取手机验证码
	 * @param Request $request
	 * @return string
	 */
	public function get_code(Request $request) {
		$input = $request->all();
		if(!isset($input["phone"])) {
			$result = ['success'=>'false',"code"=>"-1","value"=>'请输入手机号'];//手机号不能为空
			return json_encode($result);
		}
		$code = rand("100000","999999");
		$appid = "1400134205";
		$appkey = "324182372a0cf311b3c10eee76f04d09";
		$templateId = "182782";
		$time = time() + 60*60*5;
		$data = [
			"phone" => $input["phone"],
			"code" => $code,
			"endtime" => $time,
			"type" => 1
		];
		DB::table("boke_code")->insert($data);
		try {
			$msender = new SmsMultiSender($appid, $appkey);
			$params = [$code,"5"];
			$result = $msender->sendWithParam("86", [$input["phone"]],
				$templateId, $params, "", "", "");  // 签名参数未提供或者为空时，会使用默认签名发送短信
			$rsp = json_decode($result);
			return($result);
		} catch(\Exception $e) {
			echo var_dump($e);
		}
	}


	public function email_code(Request $request) {
//		$dbMail = new db();
		$mail = new PHPMailer(); //实例化

		$mail->IsSMTP(); // 启用SMTP

//		$mail->Host = "smtp.163.com"; //SMTP服务器 163邮箱例子
		//$mail->Host = "smtp.126.com"; //SMTP服务器 126邮箱例子
		$mail->Host = "smtp.qq.com"; //SMTP服务器 qq邮箱例子

		$mail->Port = 25;  //邮件发送端口
		$mail->SMTPAuth   = true;  //启用SMTP认证

		$mail->CharSet  = "UTF-8"; //字符集
		$mail->Encoding = "base64"; //编码方式

		$mail->Username = "1091552454@qq.com";  //你的邮箱
		$mail->Password = "jinbono.2";  //你的密码
		$mail->Subject = "【主题】这是邮件的主题"; //邮件标题

		$mail->From = "1091552454@qq.com";  //发件人地址（也就是你的邮箱）
		$mail->FromName = "杨康";   //发件人姓名


//		$name_email = $dbMail->getEmail();
		$name_email = array(
			array("name" => "杨康" , "email" =>"920608325@qq.com"),
			);
		$path = "./sendEmail/";
//		$template = file_get_contents("./template.html");//定义发送模版
		$template = "xml version='1.0' encoding='utf-8'";
		foreach ($name_email as $key => $value) {

			$address = $value['email'];//收件人email
			$mail->AddAddress($address,$value['email']);    //添加收件人1（地址，昵称）
			$attachment = $value['name']."-".$value['email'];
			$file = $path.$value['email']."-vip.html";
			$mail->AddAttachment($file,$attachment.".html"); // 添加附件,并指定名称,,记住要添加附件尾椎

			$mail->IsHTML(true); //支持html格式内容
			//$mail->AddEmbeddedImage("test.jpg", "my-attach", "test.jpg"); //设置邮件中的图片
			$mail->Body = $template; //邮件主体内容

			//发送
			if(!$mail->Send()) {
				echo $attachment."===发送失败\n";
				file_put_contents("error.txt", $attachment."===发送失败\n" , FILE_APPEND);
				echo "error: " . $mail->ErrorInfo;
				continue ;
			} else {
//				$status = $dbMail->updateEmail($value['email']);
//				if ($status) {
//					echo $attachment."===发送成功\n";
//					file_put_contents("success.txt", $attachment."===发送成功-".date('Y-m-d H:i:s')."\r\n" , FILE_APPEND);
//				}else{
//					echo $attachment."===发送失败\n";
//					file_put_contents("error.txt", $attachment."===发送失败".date('Y-m-d H:i:s')."\r\n", FILE_APPEND);
//				}
			}
		}
	}
}
?>